<template>
  <div class="task-create">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>配置任务</span>
      </div>
      <el-form ref="form" :model="form" label-width="80px">
        <el-form-item label="就诊人">
          <el-select v-model="form.cardId" filterable placeholder="请选择就诊人" @change="handleChangeCard">
            <!-- 选择一级菜单 -->
            <el-option
              v-for="item in cardList"
              :key="item.cardId"
              :label="`${item.patientName}--${item.cardTypeName}`"
              :value="item.cardId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="预约时间">
          <el-col :span="4">
            <el-date-picker placeholder="选择日期" v-model="form.appointmentDate"  value-format="yyyy-MM-dd"></el-date-picker>
          </el-col>

          <el-col :span="4">
            <el-select v-model="form.appointmentRange" placeholder="">
              <el-option label="上午" value="0"></el-option>
              <el-option label="下午" value="1"></el-option>
            </el-select>
          </el-col>
        </el-form-item>
        <el-form-item label="就诊日期">
          <el-col :span="4">
            <el-date-picker placeholder="选择日期" v-model="form.treatmentDate"  value-format="yyyy-MM-dd"></el-date-picker>
          </el-col>

          <el-col :span="4">
            <el-select v-model="form.treatmentRange" placeholder="">
              <el-option label="上午" value="0"></el-option>
              <el-option label="下午" value="1"></el-option>
            </el-select>
          </el-col>
        </el-form-item>
        <el-form-item label="选择科室">
          <el-cascader
            v-model="selectedDept"
            :options="deptList"
            @change="handleCascaderChange"
            filterable
            placeholder="请选择科室"
            :props="{ checkStrictly: true, value: 'value', label: 'label', children: 'children' }"
            style="width: 300px;"
          ></el-cascader>
        </el-form-item>
        <el-form-item label="选择专家">
          <el-select v-model="form.doctorId" filterable placeholder="请选择专家" @change="handleChangeDoctor">
            <el-option
              v-for="item in doctorList"
              :key="item.doctorId"
              :label="`${item.doctorName}--${item.deptName}`"
              :value="item.doctorId"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="执行方式">
          <el-select v-model="form.status" placeholder="请选择执行方式">
            <!-- 选择一级菜单 -->
            <el-option label="手动执行" value="0"></el-option>
            <el-option label="自动执行" value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="服务器">
          <el-select v-model="form.server" placeholder="请选择服务器">
            <!-- 选择一级菜单 -->
            <el-option label="主服务器" value="0"></el-option>
            <el-option label="子服务器1" value="1"></el-option>
            <el-option label="子服务器2" value="2"></el-option>
            <el-option label="子服务器3" value="3"></el-option>
            <el-option label="子服务器4" value="4"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">立即创建</el-button>
          <el-button @click="onCancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>

</template>
<script>
import {
  cardList,
  configuration,
  selDoctorListByMoreTerm,
  selFirstDept
} from '@/services/mother'
export default {
  name: 'TaskConfig',
  data () {
    return {
      form: {
        id: '',
        cardId: '',
        patientName: '',
        deptName: '',
        deptCode: '',
        docName: '',
        doctorId: '',
        treatmentDate: '',
        treatmentRange: '',
        appointmentDate: '',
        appointmentRange: '',
        status: '',
        server: '0',
        campusCode: ''
      },
      cardList: [],
      deptList: [],
      selectedDept: [],
      doctorList: []
    }
  },
  created () {
    // 加载上级菜单信息
    this.userCards()
    this.selTree()
  },
  methods: {
    async onSubmit () {
      this.form.id = this.$route.params.id
      const { data } = await configuration(this.form)
      if (data.code === 200) {
        this.$message.success('任务配置成功')
        await this.$router.push('/mother')
      } else {
        this.$message.error('任务配置失败')
      }
    },
    async userCards () {
      // 检测是否存在路由参数 id, 并进行对应处理
      const id = this.$route.params.id || 18
      // 请求菜单数据（上级菜单数据）
      const { data } = await cardList({
        id: id
      })
      if (data.code === 200) {
        // 将上级菜单数据保存，进行数据绑定
        this.cardList = data.data
      }
    },
    async selTree () {
      // 检测是否存在路由参数 id, 并进行对应处理
      const id = this.$route.params.id || 18
      // 请求菜单数据（上级菜单数据）
      const { data } = await selFirstDept({
        id: id
      })
      if (data.code === 200) {
        // 将上级菜单数据保存，进行数据绑定
        this.deptList = this.buildCascaderOptions(data.data.deptRespVos)
      }
    },
    buildCascaderOptions (deptRespVos) {
      return deptRespVos.map(area => {
        const hasDepts = area.deptRespVos && area.deptRespVos.length > 0
        return {
          value: area.treeId,
          label: area.treeName,
          children: hasDepts ? this.buildCascaderOptions(area.deptRespVos) : undefined,
          isLeaf: !hasDepts
        }
      })
    },
    findDeptNameById (deptList, id) {
      let name = ''
      function traverse (depts) {
        for (const dept of depts) {
          if (dept.value === id) {
            name = dept.label
            return
          }
          if (dept.children) {
            traverse(dept.children)
          }
        }
      }
      traverse(deptList)
      return name
    },
    async handleCascaderChange (value) {
      if (value && value.length > 0) {
        // 获取第一层（根层）的treeId
        const rootTreeId = value[0]
        // 获取最后一层的treeId
        const lastTreeId = value[value.length - 1]
        // 从deptList中查找最后一层的treeName
        const lastTreeName = this.findDeptNameById(this.deptList, lastTreeId)
        // 更新表单数据
        this.form.campusCode = rootTreeId // 存储第一层的treeId
        this.form.deptName = lastTreeName // 存储最后一层的treeName
        this.form.deptCode = lastTreeId // 存储最后一层的treeId
        // 根根据最后一层的treeid 调用
        const id = this.$route.params.id
        // 请求菜单数据（上级菜单数据）
        const { data } = await selDoctorListByMoreTerm({
          pageNum: '1',
          pageSize: '100',
          query: {
            channelCode: 'PATIENT_WECHAT_APPLET',
            organCode: 'HXD2',
            interRangfaceIndex: '',
            deptId: lastTreeId,
            isHaveNo: 'false',
            selectionTypeId: '',
            bizIndex: '',
            scheduleDate: '',
            keyWord: '',
            keyWordType: 'doctorName'
          },
          id: id
        })
        if (data.code === 200) {
          this.doctorList = data.data.content // 确保这里是正确的数据路径
        } else {
          // 处理错误或设置默认值
          this.doctorList = []
        }
      } else {
        console.error('selectedData is undefined or not an array.')
      }
    },
    async fetchDoctors (deptId) {
      let obj = {}
      obj = this.deptList.find((item) => { // this.areaList 是通过接口请求下来的区域列表
        return item.treeId === deptId // 筛选出匹配数据
      })
      this.form.deptCategoryName = obj.treeName
      const id = this.$route.params.id
      const response = await selDoctorListByMoreTerm({
        id: id,
        deptId: deptId
      })
      if (response && response.data && response.data.code === 200) {
        this.doctorList = response.data.data
      }
    },
    async handleChangeCard (value) {
      let obj = {}
      obj = this.cardList.find((item) => { // this.areaList 是通过接口请求下来的区域列表
        return item.cardId === value // 筛选出匹配数据
      })
      this.form.patientName = obj.patientName
    },
    handleChangeDoctor (selectedDoctorId) {
      // 从 doctorList 中找到选中的医生信息
      const selectedDoctor = this.doctorList.find(doctor => doctor.doctorId === selectedDoctorId)
      if (selectedDoctor) {
        // 更新 form 中的 doctorId 和 docName
        this.form.doctorId = selectedDoctor.doctorId
        this.form.docName = selectedDoctor.doctorName
      } else {
        // 如果没有找到医生，可以清除 form 中的字段或设置为默认值
        this.form.doctorId = ''
        this.form.docName = ''
      }
    },
    onCancel () {
      // 设置取消状态，让父组件处理
      this.$router.push('/task')
    }
  }
}
</script>
<style scoped lang="scss">

</style>
